package com.lighting.smssystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lighting.smssystem.model.Template;
import com.lighting.smssystem.service.IMiaodiyunSmsService;
import com.lighting.smssystem.utils.HttpUtil;
import com.lighting.smssystem.utils.Md5Util;
import com.lighting.smssystem.utils.SmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MiaodiyunSmsServiceImpl implements IMiaodiyunSmsService {

    @Value("${sms.miaodiyun.sendUrl}")
    private String sendUrl;

    @Value("${sms.miaodiyun.authToken}")
    private String authToken;

    @Value("${sms.miaodiyun.accountSid}")
    private String accountSid;


    @Override
    public SmsResponse sendMsg(Template template, List<String> phone, Map<String, String> param) {
        ArrayList<String> list = param.keySet().stream()
                .sorted(Comparator.comparingInt(Integer::parseInt))
                .map(param::get)
                .collect(Collectors.toCollection(ArrayList::new));

        String timestamp = String.valueOf(System.currentTimeMillis());
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("accountSid", accountSid);
        params.add("to", phone.stream().collect(Collectors.joining(",")));
        params.add("timestamp", timestamp);
        params.add("sig", Md5Util.encode(accountSid + authToken + timestamp));
        params.add("templateid", String.valueOf(template.getTemplateExtId()));
        params.add("param", list.stream().collect(Collectors.joining(",")));

        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        params.add("Content-type", "application/x-www-form-urlencoded");

        String result = HttpUtil.post(this.sendUrl, params, header);
        log.info(result);
        return JSON.parseObject(result, new TypeReference<SmsResponse>() {});
    }
}
